<style>
    .layui-input-inline{margin-top:10px;}
</style>
<div class="layui-card-header layui-card">
    <span class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">首页</a>
        <a><cite>代付管理</cite></a>
        <a><cite>代付订单</cite></a>
    </span>
</div>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li class="layui-this">代付订单列表</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-row">
                    <form action="" id="exportForm" method="post">
                        <input name="Authorization" id='exportHiddenInput' type="hidden"/>
                        <div class="layui-form" style="float:right; margin-bottom: 10px;">
                            <div id="timeDiv" class="layui-form-item" style="margin:0;">
                                <div class="layui-input-inline">
                                    <input type="text" name="mchId" id="searchMchId" placeholder="商户ID" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-input-inline">
                                    <input type="text" name="accountName" id="searchAccountName" placeholder="账户名" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-input-inline">
                                    <input type="text" name="agentpayOrderId" id="searchAgentpayOrderId" placeholder="代付单号" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-input-inline">
                                    <input type="text" name="mchOrderNo" id="searchMchOrderNo" placeholder="商户单号" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-input-inline">
                                    <input type="text" name="operatorUserId" id="searchOperatorUserId" placeholder="操作人ID" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-input-inline">
                                    <select name="agentpayChannel" id="searchAgentpayChannel" lay-search="">
                                        <option value="">代付渠道</option>
                                        <option value="1">商户后台</option>
                                        <option value="2">API接口</option>
                                    </select>
                                </div>
                                <div class="layui-input-inline">
                                    <select name="status" id="searchStatus" lay-search="">
                                        <option value="">状态</option>
                                        <option value="0">待处理</option>
                                        <option value="1">处理中</option>
                                        <option value="2">成功</option>
                                        <option value="3">失败</option>
                                        <option value="4">待审核</option>
                                        <option value="5">待二次确认</option>
                                    </select>
                                </div>
                                <div class="layui-input-inline" style="width: auto;">
                                    <label class="layui-form-label">自动刷新</label>
                                    <input type="checkbox" lay-filter="offlineRechargeAutoRefCheckbox" lay-skin="switch" />
                                </div>
                                <div class="layui-input-inline" style="width: auto;">
                                    <a id="search" offlineRechargeAutoRef="false" subTime="9" initSubTime="9" class="layui-btn search" data-type="reload"><i class="layui-icon layui-icon-search"></i>搜索</a>
                                </div>
                            </div>
                        </div>
                    </form>
                    <div class="layui-form-item">
                        <blockquote class="layui-elem-quote" id="amountTip">
                            订单数:<sapn id="allTotalCount" style="color: blue; margin-right: 10px;"></sapn>
                            代付金额:<span id="allTotalAmount" style="color: blue; margin-right: 10px;"></span>
                            代付费用:<span id="allTotalFee" style="color: green; margin-right: 10px;"></span>
                            扣减金额:<span id="allTotalSubAmount" style="color: green; margin-right: 10px;"></span>
                        </blockquote>
                    </div>
                </div>
                    <table id="jsList"  lay-filter="jsList"></table>
            </div>
        </div>
    </div>
</div>

<div class="layui-tab-content" id="privateKeyDiv" style="display: none">
    <form class="layui-form center" lay-filter="privateKeyDivForm">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">状态修改为</label>
                <div class="layui-input-block">
                    <input type="radio" name="reissueStatus" value="2" title="成功">
                    <input type="radio" name="reissueStatus" value="3" title="失败">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">是否发通知</label>
                <div class="layui-input-block">
                    <input type="radio" name="isNotifyMch" value="true" checked="checked" title="发送">
                    <input type="radio" name="isNotifyMch" value="false" title="不发">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">平台超级密码</label>
            <div class="layui-input-block" style="width: 220px">
                <input type="password" id="password" name="amount" lay-verify="required" placeholder="请输入超级密码" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="margin-left: 20%">
            <div class="layui-input-block">
                <button type="button" lay-filter="btnPrivateKey" lay-submit class="layui-btn layui-btn-sm">确认补单</button>
            </div>
        </div>
    </form>
</div>

<script>
     //标题内容模板
     var tplEdit = function(d){
         _result = "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='detail'><i class='layui-icon layui-icon-about'></i>详情</a>" +
                     "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='transResult'><i class='layui-icon layui-icon-about'></i>上游结果</a>";

         if(d.status == 1 || d.status == 2 || d.status == 3) {
             _result += "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='reissue'>补单</a>";
         }else{
             _result += "<a class='layui-btn layui-btn-primary layui-btn-xs layui-btn-disabled'>补单</a>";
         }

         return _result;
     };

     var tplStatus = function(d){
         if(d.status == 0) {
             return '<span class="layui-badge layui-bg-blue">待处理</span>';
         }else if(d.status == 1) {
             return '<span class="layui-badge layui-bg-orange">处理中</span>';
         }else if(d.status == 2) {
             return '<span class="layui-badge layui-bg-green">成功</span>';
         }else if(d.status == 3) {
             return '<span class="layui-badge">失败</span>';
         }else if(d.status == 4) {
             return '<span class="layui-badge layui-bg-orange">待审核</span>';
         }else if(d.status == 5) {
             return '<span class="layui-badge layui-bg-blue">待二次确认</span>';
         }
     };

     var tplAgentpayChannel = function(d){
         if(d.agentpayChannel == 1) {
             return '商户后台';
         }else if(d.agentpayChannel == 2) {
             return 'API接口';
         }
     };

     layui.use(['table','util','admin', 'timePick'], function(){
        var table = layui.table
        ,$ = layui.$
        ,admin = layui.admin
        ,timePick = layui.timePick
        ,element = layui.element
        ,view = layui.view
        ,form = layui.form;

         timePick.init();  //第一个参数表示开始时间   第二个表示结束时间   0,0今天   -1,-1昨天   -7,0近一周   以此类推
        element.render('breadcrumb', 'breadcrumb');//渲染导航信息

         var router = layui.router();
         if(router.search.searchState){ //包含 状态初始值

             //选中状态
             $("#searchStatus option[value='"+router.search.searchState+"']").prop('selected', true);
         }

         //导出参数初始化
         var tokenParamsName = layui.setter.request.tokenName;
         $('#exportHiddenInput').attr('name', tokenParamsName).val(layui.data(layui.setter.tableName)[tokenParamsName]);
         $('#exportForm').attr('action' , layui.setter.baseUrl+'/agentpay/exportExcel');

         $.setCountResult = function(mchId, supplierExecId, accountName, agentpayOrderId, transOrderId, status, agentpayChannel, mchOrderNo, operatorUserId, createTimeStart, createTimeEnd) {
             admin.req({
                 type: 'get',
                 url: layui.setter.baseUrl + '/agentpay/count',
                 data: {
                     mchId : mchId,
                     supplierExecId: supplierExecId,
                     accountName : accountName,
                     agentpayOrderId : agentpayOrderId,
                     transOrderId : transOrderId,
                     status : status,
                     agentpayChannel: agentpayChannel,
                     mchOrderNo: mchOrderNo,
                     operatorUserId: operatorUserId,
                     createTimeStart : createTimeStart,
                     createTimeEnd : createTimeEnd
                 },
                 error: function(err){
                     layer.alert(JSON.stringify(err.field), {
                         title: '错误提示'
                     })
                 },
                 success: function(res){
                     if(res.code == 0){
                         $('#allTotalCount').html(res.data.allTotalCount);
                         $('#allTotalAmount').html("￥" + res.data.allTotalAmount/100.00);
                         $('#allTotalFee').html("￥" + res.data.allTotalFee/100.0);
                         $('#allTotalSubAmount').html("￥" + res.data.allTotalSubAmount/100.00);
                     }
                 }
             });
         };

         // 初始化统计结果
         var createTimeStart = $('#createTimeStart').val();
         var createTimeEnd = $('#createTimeEnd').val();
         var agentpayOrderId = $('#searchAgentpayOrderId').val();
         var transOrderId = $('#searchTransOrderId').val();
         var accountName = $('#searchAccountName').val().trim();;
         var mchId = $('#searchMchId').val();
         var supplierExecId = $('#searchSupplierExecId').val();
         var agentpayChannel = $("#searchAgentpayChannel").val();
         var mchOrderNo = $("#searchMchOrderNo").val();
         var operatorUserId = $("#searchOperatorUserId").val();
         var status = $("#searchStatus").val();
         $.setCountResult(mchId, supplierExecId, accountName, agentpayOrderId, transOrderId, status, agentpayChannel, mchOrderNo, operatorUserId, createTimeStart, createTimeEnd);

        table.render({
            elem: '#jsList'
            ,id: "tableReload"
            ,url: layui.setter.baseUrl + '/agentpay/list'
            ,toolbar: true //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter',{
                title: '导出'
                ,layEvent: 'export'
                ,icon: 'layui-icon-export'
            }] //, 'exports'
            ,where: {
                access_token: layui.data(layui.setter.tableName).access_token,
                createTimeStart: createTimeStart,
                createTimeEnd: createTimeEnd
            }
            ,cols: [[
                {field: 'mchId', title: '商户ID'}
                ,{field: 'agentpayOrderId', title: '代付单号'}
                ,{field: 'mchOrderNo', title: '商户单号'}
                // ,{field: 'transOrderId', width: 220, title: '转账单号'}
                ,{field: 'accountName',title: '账户名'}
                ,{field: 'accountNo',title: '账号'}
                ,{field: 'amount', title: '代付金额(元)',templet: '<div>{{d.amount/100}}</div>' }
                ,{field: 'fee', title: '手续费(元)',templet: '<div>{{d.fee/100}}</div>' }
                ,{field: 'fee', title: '扣减账户金额(元)',templet: '<div>{{d.subAmount/100}}</div>' }
                ,{field: 'status',title: '状态',templet: tplStatus}
                ,{field: 'agentpayChannel',title: '代付渠道',templet: tplAgentpayChannel}
                ,{field: 'createTime',  title: '时间', width: 200, templet: '<div>{{ layui.util.toDateString(d.createTime) }}</div>' }
                ,{field: 'edite', title: '操作', width: 250, fixed: 'right', templet: tplEdit }
            ]]
            ,page: true
            ,skin: 'line'
        });

         //监听工具条
         table.on('tool(jsList)', function(obj){
             var data = obj.data;
             if(obj.event === 'detail'){
                 // location.href = layui.setter.baseLocal + "agentpay/list/detail/agentpayOrderId=" + data.agentpayOrderId;
                 view.xxpayPopup("详情", "agentpay/list/detail", {agentpayOrderId: data.agentpayOrderId}, {btn: false});
             } else if(obj.event == 'transResult') {
                 if(data.transOrderId == null || data.transOrderId == '') {
                     layer.alert("没有转账订单号,不能查询");
                     return;
                 }
                 layer.msg('正在查询代付通道代付结果...', {icon: 16});
                 admin.req({
                     type: 'post',
                     url: layui.setter.baseUrl + '/agentpay/trans_query',
                     data: {
                         transOrderId: data.transOrderId
                     },
                     error: function(err){
                         layer.alert(err);
                     },
                     success: function(res){
                         layer.closeAll('loading');
                         if(res.code == 0){
                             layer.open({
                                 title: '订单:' + data.agentpayOrderId
                                 ,content: res.data
                             });
                         }
                     }
                 });
             }else if (obj.event === 'reissue') {
                 // 置空谷歌验证码
                 $("#code").val("");
                 layer.open({
                     title: '代付补单',
                     type: 1,
                     shade: 0,
                     area: '500px',
                     content: $('#privateKeyDiv')
                 });
                 //监听提交
                 form.on('submit(btnPrivateKey)', function (data) {
                     var superPassword = $('#password').val();
                     if(!superPassword) return layer.msg('请输入平台超级密码！');

                     var reissueStatus = $("input[name='reissueStatus']:checked").val();
                     var isNotifyMch = $("input[name='isNotifyMch']:checked").val();
                     // console.log("code:" + code + ",reissueStatus:" + reissueStatus + ",isNotifyMch:" + isNotifyMch);
                     if(reissueStatus == 'undefined' || reissueStatus == undefined) {
                         layer.alert("请选中状态");
                         return;
                     }
                     // console.log("status:" + obj.data.status);
                     if(obj.data.status == 2 && reissueStatus == 2) {
                         layer.alert("当前代付已经成功,不能转为成功");
                         return;
                     }
                     if(obj.data.status == 3 && reissueStatus == 3) {
                         layer.alert("当前代付已经失败,不能转为失败");
                         return;
                     }

                     admin.req({
                         type: 'post',
                         url: layui.setter.baseUrl + '/agentpay/reissue',
                         data: {
                             superPassword: superPassword,
                             agentpayOrderId: obj.data.agentpayOrderId,
                             reissueStatus : reissueStatus,
                             isNotifyMch : isNotifyMch
                         },
                         error: function(err){
                             layer.alert(err);
                         },
                         success: function(res){
                             layer.closeAll('loading');
                             if(res.code == 0){
                                 layer.alert(res.msg, {title: '提示'}, function (index) {
                                     table.reload("tableReload");
                                     layer.closeAll();
                                 });
                             }
                         }
                     });

                 })
             }
         });

         //头工具栏事件
         table.on('toolbar(jsList)', function(obj){
             // var checkStatus = table.checkStatus(obj.config.id);
             switch(obj.event){
                 //自定义头工具栏右侧图标 - 提示
                 case 'export':
                     layer.confirm('确认导出该搜索条件下的列表吗？', function(index){
                         layer.close(index);
                         $("#exportForm").submit();
                     });
                     break;
             };
         });

         // 搜索
         var $ = layui.$, active = {
             reload: function(){
                 var createTimeStart = $('#createTimeStart').val();
                 var createTimeEnd = $('#createTimeEnd').val();
                 var agentpayOrderId = $('#searchAgentpayOrderId').val();
                 var transOrderId = $('#searchTransOrderId').val();
                 var accountName = $('#searchAccountName').val().trim();;
                 var mchId = $('#searchMchId').val();
                 var supplierExecId = $('#searchSupplierExecId').val();
                 var agentpayChannel = $("#searchAgentpayChannel").val();
                 var mchOrderNo = $("#searchMchOrderNo").val();
                 var operatorUserId = $("#searchOperatorUserId").val();
                 var status = $("#searchStatus").val();
                 $.setCountResult(mchId, supplierExecId, accountName, agentpayOrderId, transOrderId, status, agentpayChannel, mchOrderNo, operatorUserId, createTimeStart, createTimeEnd);
                 //执行重载
                 table.reload('tableReload', {
                     page: {
                         curr: 1 //重新从第 1 页开始
                     }
                     ,where: {
                         accountName: accountName,
                         agentpayOrderId: agentpayOrderId,
                         transOrderId: transOrderId,
                         mchId: mchId,
                         supplierExecId: supplierExecId,
                         createTimeStart : createTimeStart,
                         createTimeEnd : createTimeEnd,
                         agentpayChannel: agentpayChannel,
                         mchOrderNo: mchOrderNo,
                         operatorUserId: operatorUserId,
                         status : status
                     }
                 });
             }
         };
         $('#search').on('click', function() {
             var type = $(this).data('type');
             active[type] ? active[type].call(this) : '';
             return false;
         });

         form.on("switch(offlineRechargeAutoRefCheckbox)", function(data){
             if(data.elem.checked){ //开启
                 $("#search[offlineRechargeAutoRef]").attr("offlineRechargeAutoRef", "true");
             }else{
                 $("#search[offlineRechargeAutoRef]").attr("offlineRechargeAutoRef", "false");
             }
         });

         // 渲染表单
         form.render();

     });

     //定时刷新  定时任务,  先清除， 后新增
     if(typeof(alipayCashInterval) != 'undefined'){
         window.clearInterval(alipayCashInterval);
     }

     var alipayCashInterval = window.setInterval('processRef()', 1000);  //每秒执行

     function processRef(){ //处理刷新任务

         var searchBtn = layui.jquery("#search[offlineRechargeAutoRef]");
         if(searchBtn.length > 0){

             if(searchBtn.attr("offlineRechargeAutoRef") != "true"){ //未开启
                 return searchBtn.html('<i class="layui-icon layui-icon-search"></i>'+"搜索");
             }

             //开启定时刷新
             var subTime = searchBtn.attr('subTime') * 1;
             if(subTime <= 0){
                 layui.jquery('#search').click();
                 subTime = searchBtn.attr('initSubTime') * 1;
             }
             searchBtn.html('<i class="layui-icon layui-icon-search"></i>'+"搜索（"+subTime+"s）");
             subTime--;
             searchBtn.attr('subTime', subTime);

         }else{   //当查询控件不存在不在内，说明不是本页面，删除该定时任务器
             window.clearInterval(alipayCashInterval);
         }
     }


</script>